package levelrewind.android.app;

import java.util.Random;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Session;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.greystripe.sdk.GSMobileBannerAdView;

import levelrewind.android.app.model.PictureHandler;
import levelrewind.android.app.model.RestDataHandler;
import levelrewind.android.app.model.Util;
import levelrewind.android.app.model.Util.Emotion;
import levelrewind.android.app.vo.Person;
import levelrewind.android.app.vo.PersonPlace;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class PostGameActivity extends Activity {

	private ImageView pic;
	private TextView game_score_text, prev_pos_text, new_pos_text, one_place_up_text, top_five_text, first_place_text;
	private TextView game_score, prev_pos, new_pos, one_place_up, top_five, first_place;
	private Button play_again, back, post;
	private Person person;
	private int gameID;
	private long score;
	private GSMobileBannerAdView adBanner;
	private Random rand = new Random();
	private Emotion curEmotion;
	
	private final int NEW_GAME = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initialize();
	}
	
	
	private void initialize() {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.game_result);
		
		startGameActivity();
	        
        initializeViews();
        
		Bundle bn = new Bundle();
		bn = getIntent().getExtras();
		if (bn != null) {
			person = (Person)Util.getBundleObject(bn);
			gameID = bn.getInt("selectedGameID");
		}
		
		play_again.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startGameActivity();
			}
		});
		
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setResult(RESULT_OK);      
				finish();
			}
		});
		
		post.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				postToFb();
			}
		});
		
		//Add banner
    	adBanner = (GSMobileBannerAdView)this.findViewById(R.id.gsBanner);
    	adBanner.refresh();
    	
    	//Add banner under layout
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		params.addRule(RelativeLayout.ABOVE, R.id.gsBanner);
    	LinearLayout main = (LinearLayout)findViewById(R.id.result_view);
    	main.setLayoutParams(params);
	}
	
	private void startGameActivity() {
		// Start game
    	Intent intent = new Intent();
    	intent.setClassName("com.levelrewind.zombiefans", "com.levelrewind.zombiefans.ZombieActivity");
//    	intent.setClassName("com.example.android.snake", "com.example.android.snake.Snake");
    	startActivityForResult(intent, NEW_GAME);
 
	}
	
	public void postToFb() {
		Bundle params = new Bundle();
		
		PersonPlace pp = person.getPersonPlace();
		if (pp.getPlaceBefore() > pp.getPlaceNow())
		{
			params.putString("description", getString(R.string.post_facebook_rank_desc, FacebookFragment.loggedInUser.getName(), person.getName(), pp.getPlaceBefore(), pp.getPlaceNow(), score));
			params.putString("name", getString(R.string.post_facebook_rank_name, person.getName(), pp.getPlaceNow()));
		}
		else
		{
			switch (rand.nextInt(3)) {
			case 0:
				params.putString("description", getString(R.string.post_facebook_desc1, FacebookFragment.loggedInUser.getName(), score, person.getName()));
				break;
			case 1:
				params.putString("description", getString(R.string.post_facebook_desc2, FacebookFragment.loggedInUser.getName(), score, person.getName()));
				break;
			case 2:
				params.putString("description", getString(R.string.post_facebook_desc3, FacebookFragment.loggedInUser.getName(), score, person.getName()));
				break;
			}
			
			switch (rand.nextInt(3)) {
			case 0:
				params.putString("name", getString(R.string.post_facebook_name1, person.getName()));
		        break;
			case 1:
				params.putString("name", getString(R.string.post_facebook_name2, person.getName()));
		        break;
			case 2:
				params.putString("name", getString(R.string.post_facebook_name3, person.getName()));
		        break;
			}
		}
		
		params.putString("caption", getString(R.string.post_facebook_cap));
		params.putString("picture", person.getPicPath().get(curEmotion).getPath());
        params.putString("link", "http://www.levelrewind.com");
        
        publishFeedDialog(params);
		//FacebookHandler.facebook.dialog(PostGameActivity.this, "feed", params, new UpdateStatusListener());
	}
	
	private void initializeViews()
	{
		pic = (ImageView)findViewById(R.id.game_person);
		
		game_score_text = (TextView)findViewById(R.id.game_score_text);
		prev_pos_text = (TextView)findViewById(R.id.prev_pos_text);
		new_pos_text = (TextView)findViewById(R.id.new_pos_text);
		one_place_up_text = (TextView)findViewById(R.id.one_place_up_text);
		top_five_text = (TextView)findViewById(R.id.to_top_five_text);
		first_place_text = (TextView)findViewById(R.id.to_first_place_text);
		
		game_score = (TextView)findViewById(R.id.game_score);
		prev_pos = (TextView)findViewById(R.id.prev_pos);
		new_pos = (TextView)findViewById(R.id.new_pos);
		one_place_up = (TextView)findViewById(R.id.one_place_up);
		top_five = (TextView)findViewById(R.id.to_top_five);
		first_place = (TextView)findViewById(R.id.to_first_place);
		play_again = (Button)findViewById(R.id.play_again);
		back = (Button)findViewById(R.id.back_overview);
		post = (Button)findViewById(R.id.post);
		
		game_score_text.setTypeface(Util.customFont(this));
		prev_pos_text.setTypeface(Util.customFont(this));
		new_pos_text.setTypeface(Util.customFont(this));
		one_place_up_text.setTypeface(Util.customFont(this));
		top_five_text.setTypeface(Util.customFont(this));
		first_place_text.setTypeface(Util.customFont(this));
		
		game_score.setTypeface(Util.customFont(this));
		prev_pos.setTypeface(Util.customFont(this));
		new_pos.setTypeface(Util.customFont(this));
		one_place_up.setTypeface(Util.customFont(this));
		top_five.setTypeface(Util.customFont(this));
		first_place.setTypeface(Util.customFont(this));
		play_again.setTypeface(Util.customFont(this));
		back.setTypeface(Util.customFont(this));
		post.setTypeface(Util.customFont(this));
	}
	
	private void updatePostGameView()
	{
		PersonPlace pp = person.getPersonPlace();
		
		RestDataHandler dataHandler = new RestDataHandler(this);
		dataHandler.updatePersonScoreOnDevice(person.getId(), pp.getTotalScore());
		
		// Display persons picture with difference emotion depends on score
		if (pp.getPlaceNow() == pp.getPlaceBefore()){
			curEmotion = Emotion.NORMAL;
			PictureHandler.viewImageFromDevice(this, person, curEmotion, pic);
		}
		else if (pp.getPlaceNow() < pp.getPlaceBefore()) {
			curEmotion = Emotion.HAPPY;
			PictureHandler.downloadImageAndDisplay(this, person, curEmotion, pic);
		}
		else if (pp.getPlaceNow() > pp.getPlaceBefore()) {
			curEmotion = Emotion.SAD;
			PictureHandler.downloadImageAndDisplay(this, person, curEmotion, pic);
		}
		
		
		game_score.setText(Util.formatNumber(pp.getScore()) + " points");
		prev_pos.setText(pp.getPlaceBefore()+"");
		new_pos.setText(pp.getPlaceNow()+"");
		if (pp.getPlaceNow() > 1) {
			one_place_up.setText(Util.formatNumber(pp.getPointTo1PlaceUp())+" "+getString(R.string.points));
			first_place.setText(Util.formatNumber(pp.getPointToFirstPlace())+" "+getString(R.string.points));
		}
		else {
			one_place_up_text.setVisibility(View.GONE);
			first_place_text.setVisibility(View.GONE);
			
			one_place_up.setVisibility(View.GONE);
			first_place.setVisibility(View.GONE);
		}
		
		if (pp.getPlaceNow() == 2) {
			one_place_up_text.setVisibility(View.GONE);
			one_place_up.setVisibility(View.GONE);
		}
		
		if (pp.getPlaceNow() > 5) {
			top_five.setText(Util.formatNumber(pp.getPointToTop5())+" "+getString(R.string.points));
		} else {
			top_five_text.setVisibility(View.GONE);
			top_five.setVisibility(View.GONE);
		}
		
	}
	
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	if (requestCode == NEW_GAME) { 
    		if(resultCode == RESULT_OK){ 
    			Bundle extras = data.getExtras();
    			score = Long.parseLong(extras.get("score").toString());

    			postGameLoginCtrl(score);
   	     	}
    		else  { 
    			finish();
    		} 
    	}
    }
	
	private PersonPlace updatePersonScoreAndPlaceTask() {
    	long userID = FacebookFragment.loggedInUser.getId();
    	return RestDataHandler.updatePersonScoreAndPlace(userID, person.getCategoryId(), person.getId(), gameID, score);
    }
	
	public class UpdatePersonScoreAndPlaceTask extends AsyncTask<Void, Void, PersonPlace>
    {
		protected void onPostExecute(PersonPlace result)
    	{
			person.setPersonPlace(result);
			updatePostGameView();
			//postToFb();
		}
    	
    	protected PersonPlace doInBackground(Void...params) {
			return updatePersonScoreAndPlaceTask();
		}
    }
	
	private void postGameLoginCtrl(long score)
    {
		if (Util.isOnline(this)) 
    	{
			// Get facebook session
			Session session = Session.getActiveSession();
			// If user is logged in
	    	if (session.isOpened()) {
	        	// Update data after game finished
	        	new UpdatePersonScoreAndPlaceTask().execute();
			}
	    	// No Facebook connection. Try to login.
	    	else {
	    		Toast.makeText(this, "Submitting scores failed: because you are not logged in with facebook.", Toast.LENGTH_LONG).show();
	    		//retryFacebookLoginDialog().show();
	    	}
    	}
    	else {
    		Toast.makeText(this, "Submitting scores failed: because of internet connection problem.", Toast.LENGTH_LONG).show();
    		//retryDialog().show();
		}
    }
	
	public void publishFeedDialog(Bundle params) {
//	    params.putString("name", "Facebook SDK for Android");
//	    params.putString("caption", "Build great social apps and get more installs.");
//	    params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
//	    params.putString("link", "https://developers.facebook.com/android");
//	    params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

	    WebDialog feedDialog = (
	        new WebDialog.FeedDialogBuilder(this,
	            Session.getActiveSession(),
	            params))
	        .setOnCompleteListener(new OnCompleteListener() {

	            @Override
	            public void onComplete(Bundle values,
	                FacebookException error) {
	                if (error == null) {
	                    // When the story is posted, echo the success
	                    // and the post Id.
	                    final String postId = values.getString("post_id");
	                    if (postId != null) {
	                        Toast.makeText(PostGameActivity.this,"Post succesful",Toast.LENGTH_SHORT).show();
	                    } else {
	                        // User clicked the Cancel button
	                        Toast.makeText(PostGameActivity.this,"No wall post made",  Toast.LENGTH_SHORT).show();
	                    }
	                } else if (error instanceof FacebookOperationCanceledException) {
	                    // User clicked the "x" button
	                    Toast.makeText(PostGameActivity.this,"Publish cancelled", Toast.LENGTH_SHORT).show();
	                } else {
	                    // Generic, ex: network error
	                    Toast.makeText(PostGameActivity.this, "Error posting", Toast.LENGTH_SHORT).show();
	                }
	            }

	        }).build();
	    
	    feedDialog.show();
	}
	
	@SuppressWarnings("unused")
	private AlertDialog.Builder retryFacebookLoginDialog()
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_header);
        builder.setMessage(R.string.postGame_noLogin);
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		});
        builder.setPositiveButton(R.string.connect, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (Util.isOnline(getApplicationContext())) {
					//Login is Asyntask, so we have to put updateScore into the Login.onComplete
//					FacebookHandler facebookHandler = new FacebookHandler(PostGameActivity.this);
//					facebookHandler.setUpdateScore(true);
//		            facebookHandler.login();
				}
				else {
//					retryLoginDialog().show();
					retryDialog().show();
					dialog.dismiss();
				}
				
			}
		});
        builder.create();
        return builder;
    }
	
	private AlertDialog.Builder retryDialog()
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.no_network);
        builder.setMessage(R.string.try_again);
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
//				setResult(RESULT_OK);
				finish();
			}
		});
        builder.setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				postGameLoginCtrl(score);
				dialog.dismiss();
			}
		});
        builder.create();
        return builder;
    }
	
	//Update when user was not logged in
//	@Override
//    public void updatePersonScoreAndPlace(boolean isUpdateScore) {
//    	if (isUpdateScore) {
//    		new UpdatePersonScoreAndPlaceTask().execute();
//		}
//    }
	
	
	
	
}
